/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package vodjaho.lab;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Maxim A. Kanev <ask.me.makes@gmail.com> [mkanev]
 */
public class UserUtil {

    final static String[] users = new String[]{
        "mkanev;1a755bd74cd41bbe8d0bfb8ca48e9657;Max Kanev",
        "user1;ca34ff7d9e295155b189c3591f8ca195;Joey Summers",
        "user2;eb4d6d04deec283d8ace0e3a71e954ca;Kathy McBride",
        "user3;ad825eb1b8d548155de65b1fb46141e2;Andrew Devenport"
    };
    final static byte[] HEX_CHAR_TABLE = {(byte) '0', (byte) '1', (byte) '2',
        (byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7',
        (byte) '8', (byte) '9', (byte) 'a', (byte) 'b', (byte) 'c',
        (byte) 'd', (byte) 'e', (byte) 'f'};

    public static User getUset(String login, String password) {
        String md5 = "";
        try {
            MessageDigest md = MessageDigest.getInstance("md5");
            md.update(login.getBytes());
            md5 = getHexString(md.digest(password.getBytes()));
            //            System.out.println(md5);
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(UserUtil.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(UserUtil.class.getName()).log(Level.SEVERE, null, ex);
        }
        return getFromArray(login, md5);
    }

    private static User getFromArray(String login, String pwd) {
        User user = new User();
        Logger.getLogger(UserUtil.class.getName()).log(Level.INFO, "processing: {0}, {1}", new Object[]{login, pwd});
        for (String record : users) {
            Logger.getLogger(UserUtil.class.getName()).log(Level.INFO, "processing: {0}", record);
            if (!record.contains(login)) {
                continue;
            }
            if (!record.contains(pwd)) {
                continue;
            }
            user.parseString(record);
        }
        return user;
    }

    private static String getHexString(byte[] raw) throws UnsupportedEncodingException {
        byte[] hex = new byte[2 * raw.length];
        int index = 0;

        for (byte b : raw) {
            int v = b & 0xFF;
            hex[index++] = HEX_CHAR_TABLE[v >>> 4];
            hex[index++] = HEX_CHAR_TABLE[v & 0xF];
        }
        return new String(hex, "ASCII");
    }
}
